// JavaScript Document
//折叠面板组件
//该组件作为ligerLayout2的子项目，不可独立使用
(function ($)
{
    $.fn.ligerAccordion2 = function (options)
    {
        return $.ligerui.run.call(this, "ligerAccordion2", arguments);
    };

    $.fn.ligerGetAccordion2Manager = function ()
    {
        return $.ligerui.run.call(this, "ligerGetAccordion2Manager", arguments);
    };

    $.ligerDefaults.Accordion2 = {
    	basepath:'',
		url: null,
        data: null,
        textFieldName: 'name',
        idFieldName: 'id',
        iconFieldName: 'icon',
        iconpath: '',
        onClick: null,
        onSuccess: null,
        onError: null,
        onCreated: null,
		height: null,
        speed: "normal",
        expand: null,
        changeHeightOnResize: false,
        heightDiff: 0, //高度补差
        layout: null
    };
    $.ligerMethos.Accordion2 = {};

    $.ligerui.controls.Accordion2 = function (element, options)
    {
        $.ligerui.controls.Accordion2.base.constructor.call(this, element, options);
    };
    $.ligerui.controls.Accordion2.ligerExtend($.ligerui.core.UIComponent, {
        __getType: function ()
        {
            return 'Accordion2';
        },
        __idPrev: function ()
        {
            return 'Accordion2';
        },
        _extendMethods: function ()
        {
            return $.ligerMethos.Accordion2;
        },
        _init: function (){
        	$.ligerui.controls.Accordion2.base._init.call(this);
        },
        _render: function ()
        {
            var g = this, p = this.options;
            g.accordion = $(g.element);
            if (!g.accordion.hasClass("l-accordion2-panel")) g.accordion.addClass("l-accordion2-panel");
            
            if (p.height && typeof (p.height) == 'string' && p.height.indexOf('%') > 0)
            {
                g.onResize();
                if (p.changeHeightOnResize)
                {
                    $(window).resize(function ()
                    {
                        g.onResize();
                    });
                }
            }
            else
            {
                if (p.height && typeof (p.height) != 'string')
                {
                    g.height = p.heightDiff + p.height;
                    g.accordion.height(g.height);
                    g.setHeight(g.height);
                }
            }

            var pc = $.extend({}, p);
            g._setEvent();
			delete pc['data'];
			delete pc['url'];
			g.set(pc);
			if(p.url){
				g.set({ url: p.url });
			}
			else if (p.data){
				g.set({ data: p.data });
			}
        },
        _setUrl: function (value)
		{
			this.options.url = value;
			if (value)
			{
				this.options.dataType = "server";
				this.loadData(true);
			}
			else
			{
				this.options.dataType = "local";
			}
		},
		_setData: function (value)
		{
			this.loadData(this.options.data);
		},
		//刷新数据
		loadData: function (loadDataParm)
		{
			var g = this, p = this.options;
			
			var clause = null;
			var loadServer = true;
			if (typeof (loadDataParm) == "function")
			{
				clause = loadDataParm;
				p.dataType = "local";
			}
			else if (typeof (loadDataParm) == "boolean")
			{
				p.dataType = loadDataParm?"server":"local";
			}
			else if (typeof (loadDataParm) == "object")
			{
				p.dataType = "local";
				p.data = loadDataParm;
			}
			if (p.dataType == "server")
			{
				g.loadServerData();
			}
			else
			{
				g.data = p.data;
				if (clause){
					g.data = p.data = clause.call(g);
				}
				g._showData();
			}
			g.loading = false;
		},
		loadServerData: function (param, clause)
		{
			var g = this, p = this.options;
			var ajaxOptions = {
				type: 'get',
				url: p.url,
				cache: false,
				dataType: 'json',
				success: function (data)
				{
					if(typeof(data)=='string'){
						data = $.parseJSON(data);
					}
					g.trigger('success', [data]);
					
					if(!data)
					{
						g.data = [];
						g._showData();
						return;
					}
					
					g.data = data;
					g._showData.ligerDefer(g, 10, [g.data]);
				},
				error: function (XMLHttpRequest, textStatus, errorThrown)
				{
					g.data = [];
					g.trigger('error', [XMLHttpRequest, textStatus, errorThrown]);
				}
			};
			$.ajax(ajaxOptions);
		},
		_showData: function ()
        {
            var g = this, p = this.options;
            var data = g.data;
            g.accordion.empty();
            if (!data || !data.length) return;
            var d0 = data[0];
            if(d0.type!='tree' && (!d0.children || d0.children.length==0))//简单列表
            {
            	var box = $('<div class="l-accordion2-content"></div>');
            	g.accordion.append(box);
            	var ul = $('<ul class="left-oper"></ul>');
            	box.append(ul);
            	for (var i in data){
            		var itm = data[i];
        			var li = $('<li class="left-oper-li"></li>');
        			if(i==0){
        				li.addClass('first');
        			}
					if(p.layout._notEmpty(itm[p.iconFieldName])){
						li.append('<img src="'+g._getIconPath(itm[p.iconFieldName])+'" />');
					}
					li.append(itm[p.textFieldName]);
					ul.append(li);
					li.data('__itmdata', itm);
            	}
            }
            else//折叠
            {
            	g.expand = 0;
                if(p.expand=='no' || p.expand=='false'){
                	g.expand = -1;
                }else if(p.layout._notEmpty(p.expand)){
                	g.expand = parseInt(p.expand) || 0;
                	if(g.expand<0){
                		g.expand = 0;
                	}
                	if(g.expand>=data.length){
                		g.expand = data.length-1;
                	}
                }
                
                for (var i in data)
                {
                	var d = data[i];
                	var header = $('<div class="l-accordion2-header">'
                			+'<div class="l-accordion2-icon"></div>'
                			+'<div class="l-accordion2-inner"></div>'
                			+'<div class="l-accordion2-toggle"></div></div>');
                	g.accordion.append(header);
                	
	        		if(p.layout._notEmpty(d[p.iconFieldName])){
    	        		var icon = $('<img />');
    	        		icon.attr('src', g._getIconPath(d[p.iconFieldName]));
    	        		$('.l-accordion2-icon', header).append(icon);
    	        		$('.l-accordion2-inner', header).addClass('l-accordion2-inner-icon');
    	        	}else{
    	        		$('.l-accordion2-icon', header).hide();
    	        		$('.l-accordion2-inner', header).addClass('l-accordion2-inner-noicon');
    	        	}
    	        	$('.l-accordion2-inner', header).html(d[p.textFieldName]);
                	if(i==g.expand){
                		$(".l-accordion2-toggle", header).addClass("l-accordion2-toggle-open");
                	}
                	
                	var box = $('<div class="l-accordion2-content"></div>');
                	g.accordion.append(box);
                	if(d.type=='tree'){
                		var aZTree = $('<ul id="aZTree_'+(d.id||d.code)+'" class="ztree"></ul>');
                		box.append(aZTree);
                		var url = p.layout._getUrl(d.url);
            			if(url.indexOf('?')==-1)
            			{
            				url += '?';
            			}else{
            				url += '&';
            			}
            			url += 'r='+Math.random();
            			
            			var params = p.layout._getGlobalParam();
            			
            			var z = $.fn.zTree.init(aZTree, {
            				async:{
	        					enable:true,type:'get',autoParam:['id=pid','type=pdatatype','custattr=pcustattr'],otherParam: params, url: url,
	        					dataFilter: function(treeId, parentNode, responseData)
	        					{
	        						var conver = function(tnodes)
	        						{
	        							for(var i in tnodes)
	        							{
	        								var tnode = tnodes[i];
	        								if(p.layout._notEmpty(tnode.icon))
	        								{
	        									tnode.icon = g._getIconPath(tnode.icon);
	        								}
	        								if(tnode.children)
	        								{
	        									conver(tnode.children);
	        								}
	        							}
	        						};
	        						conver(responseData);
	        						return responseData;
	        					}
	        				},
	        				view:{selectedMulti:false,autoCancelSelected:false,dblClickExpand:false},
	        				callback:{
	        					onAsyncSuccess:function(event, treeId, treeNode, msg)//加载完成事件
	        					{
	        						var z = $.fn.zTree.getZTreeObj(treeId);
	        						var d = z._acdata;
	        						if(z.accordionIndex==g.expand && !z.loaded)
	        						{
	        							z.loaded = true;
	        							var nodes = z.getNodes();
	        							if(!nodes || nodes.length==0)return;
	        							var clicknode = nodes[0];
	        							if(nodes[0].notclick===true || nodes[0].notclick==='true')
	        							{
	        								var children = nodes[0].children;
	        								if(children && children.length>0){
	        									clicknode = children[0];
	        								}
	        							}
	        							z.selectNode(clicknode);
	        							$("#"+clicknode.tId+this.consts.id.A, z.setting.treeObj).click();//触发第一个节点的点击事件
	        						}
	        						//处理默认展开节点
	        						if(treeNode!=null || d.expand==null)return;
	        						var expand = d.expand.split('|')[0];
	        						if(expand!='first' && expand!='all')return;
	        						var nodes = z.getNodes();
	        						if(!nodes || nodes.length==0)return;
	        						//展开第一个节点
	        						if(expand=='first')
	        						{
	        							nodes[0].__isinitexpand=true;
	        							z.expandNode(nodes[0], true, false, true, true);
	        						}
	        						else if(expand=='all')
	        						{
	        							for(var i in nodes)
	        							{
	        								nodes[i].__isinitexpand=true;
	        								z.expandNode(nodes[i], true, false, true, true);
	        							}
	        						}
	        					},
	        					onExpand:function(event, treeId, treeNode)//展开节点事件
	        					{
	        						if(!treeNode.__isinitexpand)return;
	        						delete treeNode.__isinitexpand;
	        						
	        						var z = $.fn.zTree.getZTreeObj(treeId);
	        						var d = z._acdata;
	        						var arr = d.expand.split('|');
	        						var expand = arr[0];
	        						var level = (arr.length>1)?parseInt(arr[1]):0;
	        						if(treeNode.level>=level)return;
	        						var nodes = treeNode.children;
	        						if(!nodes || nodes.length==0)return;
	        						if(expand=='first')
	        						{
	        							nodes[0].__isinitexpand=true;
	        							z.expandNode(nodes[0], true, false, true, true);
	        						}
	        						else if(expand=='all')
	        						{
	        							for(var i in nodes)
	        							{
	        								nodes[i].__isinitexpand=true;
	        								z.expandNode(nodes[i], true, false, true, true);
	        							}
	        						}
	        					},
	        					beforeClick:function(treeId, treeNode, clickFlag)
	        					{
	        						if(treeNode.notclick===true || treeNode.notclick==='true')
	        						{
	        							return false;
	        						}
	        						return true;
	        					},
	        					onClick:function(event, treeId, treeNode, clickFlag)//节点点击事件
	        					{
	        						var z = $.fn.zTree.getZTreeObj(treeId);
	        						g.trigger('click', [treeNode, 'tree', z]);
	        						if(!treeNode.open){
	        							z.expandNode(treeNode, true, false, true, true);
	        						}
	        					}
	        				}
            			});
            			z.accordionIndex = i;
            			z._acdata = d;
                	}else{//[22]
                		var ul = $('<ul class="left-oper"></ul>');
                    	box.append(ul);
                    	var itms = d.children;
                    	if(itms){
                    		for(var j in itms){
                    			var itm = itms[j];
                    			var li = $('<li class="left-oper-li"></li>');
                    			if(j==0){
                    				li.addClass('first');
                    			}
        						if(itm[p.iconFieldName]){
        							li.append('<img src="'+g._getIconPath(itm[p.iconFieldName])+'" />');
        						}
        						li.append(itm[p.textFieldName]);
        						ul.append(li);
        						li.data('__itmdata', itm);
                    		}
                    	}
                	}//[22]
                }
            }
            
            $(".l-accordion2-toggle", g.accordion).each(function ()
            {
                if (!$(this).hasClass("l-accordion2-toggle-open") && !$(this).hasClass("l-accordion2-toggle-close"))
                {
                    $(this).addClass("l-accordion2-toggle-close");
                }
                if ($(this).hasClass("l-accordion2-toggle-close"))
                {
                    $(this).parent().next(".l-accordion2-content:visible").hide();
                }
            });
            
            $(".l-accordion2-header", g.accordion).hover(function ()
            {
                $(this).addClass("l-accordion2-header-over");
            }, function ()
            {
                $(this).removeClass("l-accordion2-header-over");
            });
            $(".l-accordion2-toggle", g.accordion).hover(function ()
            {
                if ($(this).hasClass("l-accordion2-toggle-open")){
                    $(this).addClass("l-accordion2-toggle-open-over");
                }else if ($(this).hasClass("l-accordion2-toggle-close")){
                    $(this).addClass("l-accordion2-toggle-close-over");
                }
            }, function ()
            {
                if ($(this).hasClass("l-accordion2-toggle-open")){
                    $(this).removeClass("l-accordion2-toggle-open-over");
                }else if ($(this).hasClass("l-accordion2-toggle-close")){
                    $(this).removeClass("l-accordion2-toggle-close-over");
                }
            });
            var allitms = $("> .l-accordion2-content > ul > li", g.accordion);
            allitms.hover(function ()
            {
            	if(!$(this).hasClass("current")){!$(this).addClass("hover");}
            }, function ()
            {
            	$(this).removeClass("hover");
            });
            
            g.headerHoldHeight = 0;
            $("> .l-accordion2-header", g.accordion).each(function ()
            {
                g.headerHoldHeight += $(this).height();
            });
            g.onResize();
            g.trigger('created', []);
        },
        clickItem: function(paneIndex, itemIndex)
        {
        	var g = this, p = this.options;
        	paneIndex = paneIndex || 0;
        	itemIndex = itemIndex || 0;
        	var pane = $("> .l-accordion2-content", g.accordion).eq(paneIndex);
        	if(!pane)return;
        	var li = $('> ul > li', pane).eq(itemIndex);
        	if(li){
        		li.click();
        	}
        },
        onResize: function ()
        {
            var g = this, p = this.options;
            if(p.height && p.height=='auto'){
            	g.setHeight();
            	return;
            }
            if (!p.height || typeof (p.height) != 'string' || p.height.indexOf('%') == -1) return false;
            //set accordion height
            if (g.accordion.parent()[0].tagName.toLowerCase() == "body")
            {
                var windowHeight = $(window).height();
                windowHeight -= parseInt(g.layout.parent().css('paddingTop'));
                windowHeight -= parseInt(g.layout.parent().css('paddingBottom'));
                g.height = p.heightDiff + windowHeight * parseFloat(g.height) * 0.01;
            }
            else
            {
                g.height = p.heightDiff + (g.accordion.parent().height() * parseFloat(p.height) * 0.01);
            }
            g.setHeight(g.height);
        },
        setHeight: function (height)
        {
            var g = this, p = this.options;
            if(height){
            	g.accordion.height(height);
                if(g.headerHoldHeight){
                	height -= g.headerHoldHeight;
                    $("> .l-accordion2-content", g.accordion).height(height);
                    $("> .l-accordion2-content > .ztree", g.accordion).height(height-10);
                }
            }else{
            	height = g.accordion.parent().innerHeight();
            	g.accordion.height(height);
                if(g.headerHoldHeight){
                	height -= g.headerHoldHeight;
                    $("> .l-accordion2-content", g.accordion).height(height);
                    $("> .l-accordion2-content > .ztree", g.accordion).height(height-10);
                }
            }
            
        },
        _setEvent: function ()
        {
        	var g = this, p = this.options;
        	g.accordion.bind("click.accordion2", function (e)
            {
                g._onClick(e);
            });
        },
        _getSrcElementByEvent: function (e)
        {
            var g = this;
            var obj = (e.target || e.srcElement);
            var jobjs = $(obj).parentsUntil(g.accordion[0]).add(obj).add(g.accordion);
            var fn = function (clazz)
            {
                for (var i = 0; i < jobjs.length; i++)
                {
                   if ($(jobjs[i]).hasClass(clazz)) return jobjs[i];
                }
                return null;
            };
            if (jobjs.index(this.element) == -1) return { out: true };
            var r = {
            	accordion: fn("l-accordion2-panel"),
            	header: fn("l-accordion2-header"),
                li: fn("left-oper-li"),
                ztree: fn("ztree")
            };
            if(r.li){
            	r.data = $(r.li).data('__itmdata');
            }
            return r;
        },
        _onClick: function (e)
        {
        	var g = this, p = this.options;
            var src = g._getSrcElementByEvent(e);
            if (src.out || e.which>1 || src.ztree) return;
            if(src.header){
            	var header = $(src.header);
            	var togglebtn = $(".l-accordion2-toggle:first", header);
                if (togglebtn.hasClass("l-accordion2-toggle-close"))
                {
                    togglebtn.removeClass("l-accordion2-toggle-close").removeClass("l-accordion2-toggle-close-over l-accordion2-toggle-open-over");
                    togglebtn.addClass("l-accordion2-toggle-open");
                    header.next(".l-accordion2-content").show(p.speed).siblings(".l-accordion2-content:visible").hide(p.speed);
                    header.siblings(".l-accordion2-header").find(".l-accordion2-toggle").removeClass("l-accordion2-toggle-open").addClass("l-accordion2-toggle-close");
                }
                else
                {
                    togglebtn.removeClass("l-accordion2-toggle-open").removeClass("l-accordion2-toggle-close-over l-accordion2-toggle-open-over").addClass("l-accordion2-toggle-close");
                    header.next(".l-accordion2-content").hide(p.speed);
                }
            }else if(src.li && src.data){
            	var m = $(src.li);
            	var allitms = $("> .l-accordion2-content > ul > li", g.accordion);
            	allitms.removeClass('current');
				m.removeClass("hover");
				m.addClass('current');
            	g.trigger('click', [src.data, 'list']);
            }
        },
        _getIconPath: function(iconPath)
        {
        	var g = this, p = this.options;
        	iconPath = p.layout._getUrl(iconPath);
        	if(iconPath.indexOf('http://')==0 || iconPath.indexOf('https://')==0){
        		return iconPath;
        	}
        	if(iconPath.charAt(0)=='/'){
        		return iconPath;
        	}
        	return p.iconpath + '/' + iconPath;
        }
    });


})(jQuery);
